package com.glut.campusrepair.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glut.campusrepair.dto.MaintenanceLongRecordsdto;
import com.glut.campusrepair.dto.MaintenanceRecordsdto;
import com.glut.campusrepair.dto.MaintenanceShortRecordsdto;
import com.glut.campusrepair.entity.MaintenanceRecordRequest;
import com.glut.campusrepair.entity.MaintenanceRecords;
import com.glut.campusrepair.mapper.MaintenanceRecordsMapper;
import com.glut.campusrepair.service.IMaintenanceRecordsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.Proxy;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 *  服务实现类
 *
 * @author QJC
 * @since 2024-07-21 17:24
 */
@Service
public class MaintenanceRecordsServiceImpl extends ServiceImpl<MaintenanceRecordsMapper,MaintenanceRecords> implements  IMaintenanceRecordsService {

    private static final Logger log = LoggerFactory.getLogger(MaintenanceRecordsServiceImpl.class);


    @Autowired
    MaintenanceRecordsMapper maintenanceRecordsMapper;

    @Override
    public Page<MaintenanceRecords> querypages(MaintenanceRecordsdto maintenanceRecordsdto) {
            log.info("条件查询：{}",maintenanceRecordsdto);
        // 创建分页对象
        Page<MaintenanceRecords> page = new Page<>(maintenanceRecordsdto.getPageNo(), maintenanceRecordsdto.getPageSize());
        // 创建查询条件
        QueryWrapper<MaintenanceRecords> queryWrapper = new QueryWrapper<>();
        if (maintenanceRecordsdto.getFullName()!=null && !maintenanceRecordsdto.getFullName().isEmpty()){
            queryWrapper.like("full_name",maintenanceRecordsdto.getFullName());
        }
        if (maintenanceRecordsdto.getType()!=null && !maintenanceRecordsdto.getType().isEmpty()){
            queryWrapper.eq("type",maintenanceRecordsdto.getType());
        }
        if (maintenanceRecordsdto.getStartTime() != null && maintenanceRecordsdto.getEndTime() != null) {
            queryWrapper.between("repair_time", maintenanceRecordsdto.getStartTime(), maintenanceRecordsdto.getEndTime());
        }
        // 执行分页查询
        return this.maintenanceRecordsMapper.selectPage(page, queryWrapper);
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void deletes(List<Integer> ids) {
        log.info("批量删除 IDs: {}", ids);
        maintenanceRecordsMapper.deleteByIds(ids);
    }

    /**
     * @param mainmaintenanceRecordsId
     */
    @Override
    public void deleteuser(Integer mainmaintenanceRecordsId) {
        if (mainmaintenanceRecordsId == null) {
            throw new IllegalArgumentException("ID must not be null");
        }
        maintenanceRecordsMapper.deleteById(mainmaintenanceRecordsId);
    }

    /**
     * @param maintenanceRecordsdto
     */
    @Override
    public void update(MaintenanceRecordsdto maintenanceRecordsdto) {
        maintenanceRecordsMapper.update(maintenanceRecordsdto);
    }


    /**
     * 根据当前登录用户ID查询这个用户报修的所有未评价的简洁版维修记录
     * 展示在维修记录卡片中
     */
    @Override
    public List<MaintenanceShortRecordsdto> selectByUserNo_11(Integer userNo) {

        return maintenanceRecordsMapper.selectByUserNo_11(userNo);
    }

    /**
     * 根据当前登录用户ID查询这个用户报修的所有已评价的简洁版维修记录
     * 展示在维修记录卡片中
     */
    @Override
    public List<MaintenanceShortRecordsdto> selectByUserNo_12(Integer userNo) {
        return maintenanceRecordsMapper.selectByUserNo_12(userNo);
    }

    /**
     * 根据维修记录ID查找详细版维修记录
     * @param
     */
    @Override
    public MaintenanceLongRecordsdto selectByPrimaryKey_2(Integer maintenanceRecordsId) {
        return maintenanceRecordsMapper.selectByPrimaryKey_2(maintenanceRecordsId);
    }



    @Override
    public boolean saveBatch(Collection<MaintenanceRecords> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<MaintenanceRecords> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean updateBatchById(Collection<MaintenanceRecords> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdate(MaintenanceRecords entity) {
        return false;
    }

    @Override
    public MaintenanceRecords getOne(Wrapper<MaintenanceRecords> queryWrapper, boolean throwEx) {
        return null;
    }

    @Override
    public Optional<MaintenanceRecords> getOneOpt(Wrapper<MaintenanceRecords> queryWrapper, boolean throwEx) {
        return Optional.empty();
    }

    @Override
    public Map<String, Object> getMap(Wrapper<MaintenanceRecords> queryWrapper) {
        return Map.of();
    }

    @Override
    public <V> V getObj(Wrapper<MaintenanceRecords> queryWrapper, Function<? super Object, V> mapper) {
        return null;
    }


    @Override
    public Class<MaintenanceRecords> getEntityClass() {
        return null;
    }


    @Override
    public List<MaintenanceRecords> getEmployeeRepairRecords(Integer employeeId) {
        LambdaQueryWrapper<MaintenanceRecords> queryWrapper = new LambdaQueryWrapper<>(); // 创建LambdaQueryWrapper对象，用于构建查询条件

        queryWrapper.eq(MaintenanceRecords::getEmployeeId, employeeId); // 添加等于条件到查询条件中，匹配员工ID

        return this.list(queryWrapper); // 使用父类的list方法，传入queryWrapper作为查询条件，执行查询并返回符合条件的维修记录列表
    }

    @Override
    public List<MaintenanceRecords> getNowEmployeeRepairRecords(Integer employeeId) {
        QueryWrapper<MaintenanceRecords> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("employee_id", employeeId)
                .eq("maintenance_status", "正在维修");
        List<MaintenanceRecords> maintenanceRecords = this.list(queryWrapper);
        return maintenanceRecords;
    }


    @Override
    public void upMainMaintenanceRecord(Integer employeeId){
        QueryWrapper<MaintenanceRecords> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("employee_id", employeeId)
                .eq("maintenance_status", "正在维修");
        MaintenanceRecords maintenanceRecords = getOne(queryWrapper);

        if (maintenanceRecords != null) {
            maintenanceRecords.setMaintenanceStatus("维修完毕");
            maintenanceRecords.setRecordTime(new Date());
            // 更新数据库中的记录
            updateById(maintenanceRecords);
        }

        return ;
    }

    private static final Logger logger = LoggerFactory.getLogger(MaintenanceRecordsServiceImpl.class);

    @Override
    public MaintenanceRecords getMaintenanceRecords(MaintenanceRecordRequest maintenanceRecordRequest) {
        Integer userNo = maintenanceRecordRequest.getUserNo();
        Integer employeeId = maintenanceRecordRequest.getEmployeeId();
        String employeeName = maintenanceRecordRequest.getEmployeeName();

        System.out.println("---------------------------/////"+userNo+"///////////"+employeeId+employeeName);

        QueryWrapper<MaintenanceRecords> queryWrapper = new QueryWrapper<>(MaintenanceRecords.class);
        queryWrapper.eq("user_no", userNo)
                .isNull(true,"employee_id");  // 查询 employee_id 为 null 的记录
//        MaintenanceRecords maintenanceRecords = null; //this.getOne(queryWrapper);

        List<MaintenanceRecords> list = this.list(queryWrapper);
        log.info("getMaintenanceRecords: {}",list);

        // 检查 maintenanceRecords 是否为 null
        if (list == null || list.isEmpty()) {
            throw new RuntimeException("未找到对应的维修记录");
        }
        MaintenanceRecords maintenanceRecords = list.get(0);
        Date currentDate = new Date();

        // 创建一个 SimpleDateFormat 对象并指定日期格式
        SimpleDateFormat sdfb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 将 Date 对象转换为字符串
        String formattedDate = sdfb.format(currentDate);

        // 更新员工 id
        maintenanceRecords.setEmployeeId(employeeId);
        // 更新员工名字
        maintenanceRecords.setEmployeeName(employeeName);
        // 更新维修派工时间
        maintenanceRecords.setDispatchTime(formattedDate);
        // 更新维修状态
        maintenanceRecords.setMaintenanceStatus("待接受");
        // 更新记录时间（如果这个字段和 dispatchTime 不同，保留）
        maintenanceRecords.setRecordTime(new Date());
        // 更新更新时间
        maintenanceRecords.setUpdateTime(new Date());
        log.info("saveOrUpdate: {}", maintenanceRecords);
        boolean result = updateById(maintenanceRecords);
        if (!result) {
            throw new RuntimeException("更新维修记录失败");
        }
        return maintenanceRecords;
    }
        /*String repairTimeStr = maintenanceRecordRequest.getRepairTime();
        Integer employeeId = maintenanceRecordRequest.getEmployeeId();
        String employeeName = maintenanceRecordRequest.getEmployeeName();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date repairTimeDate = sdf.parse(repairTimeStr);

            // 使用解析后的 Date 对象进行查询
            QueryWrapper<MaintenanceRecords> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("repair_time", repairTimeDate);
            System.out.println("////////////////"+repairTimeStr+"///"+ );
            MaintenanceRecords maintenanceRecords = getOne(queryWrapper);
            System.out.println("----------------------------------------");
            System.out.println(maintenanceRecords);

            // 如果没有找到记录，则创建一个新的记录
            if (maintenanceRecords == null) {
                maintenanceRecords = new MaintenanceRecords();
                maintenanceRecords.setRepairTime(repairTimeDate);
            }

            Date currentDate = new Date();
            SimpleDateFormat sdfb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = sdfb.format(currentDate);

            maintenanceRecords.setEmployeeId(employeeId);
            maintenanceRecords.setEmployeeName(employeeName);
            maintenanceRecords.setDispatchTime(formattedDate);
            maintenanceRecords.setMaintenanceStatus("待接受");
            maintenanceRecords.setUpdateTime(new Date());

            try {
                boolean result = saveOrUpdate(maintenanceRecords);
                if (!result) {
                    logger.error("保存或更新维修记录失败: {}", maintenanceRecords);
                    throw new RuntimeException("插入维修记录失败");
                }
            } catch (Exception e) {
                logger.error("保存或更新维修记录时发生异常: {}", maintenanceRecords, e);
                throw new RuntimeException("插入维修记录失败", e);
            }

            return maintenanceRecords;
        } catch (ParseException e) {
            throw new RuntimeException("无法解析日期字符串: " + repairTimeStr, e);
        }
    }*/
}
